package com.springboot.logback.utils.impllogback;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.joran.JoranConfigurator;
import com.springboot.logback.utils.ILogger;
import com.springboot.logback.utils.ILoggerFactory;
import org.slf4j.LoggerFactory;

import java.io.InputStream;

/**
 * neu
 * 2019/7/29 9:44
 *
 * @Version : 1.0
 * @Description :
 */
public class LogbackLoggerFactory implements ILoggerFactory {
    private static LoggerContext context;

    @Override
    public ILogger getLogger(String name) {
        Logger logbackLogger = context.getLogger(name);
        LogbackLogger logger = new LogbackLogger(logbackLogger);
        return logger;
    }

    @Override
    public ILogger getLogger(Class<?> clazz) {
        Logger logbackLogger = context.getLogger(clazz);
        LogbackLogger logger = new LogbackLogger(logbackLogger);
        return logger;
    }


    public LogbackLoggerFactory() throws Exception{
        initLogback();
    }

    private void initLogback() throws Exception{
        InputStream is = null;
        is = LogbackLoggerFactory.class.getResourceAsStream("logback-spring.xml");
        if(null == is){
            is = LogbackLoggerFactory.class.getResourceAsStream("/logback-spring.xml");
        }
        context = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator(); // 定义一个(JoranConfigurator)配置器
        configurator.setContext(context); // 将当前应用的logger

        context.reset(); // 清除以前的配置器中的所有内容
        try {
            configurator.doConfigure(is);
            is.close();
        } catch (Exception e) {
            throw new RuntimeException("初始化Logback日志框架出现系统级错误!", e);
        }
    }
}
